<script setup>
import { onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus';
import { Check, Close } from '@element-plus/icons-vue'
import { getWarehouseListAll, getWarehouseAreaListByWarehouseId, getWarehouseAreaTypeListByWarehouseAreaId, addWarehouseLocation, updateWarehouseLocation } from '@/api/warehouse'
const emits = defineEmits(['flash'])
const dialogFormVisible = ref(false)
const title = ref('')
const formData = ref({
  id: '',
  warehouseId: '',
  warehouseAreaId: '',
  category: '',
  localCode: '',
  localLen: '',
  localWidth: '',
  localHeight: '',
  localVolume: '',
  localBearingCapacity: '',
  tunnelNumber: '',
  shelfNumber: '',
  layerNumber: '',
  isDel: ''
})
const reset = ref(() => {
  formData.value = {
    id: '',
    warehouseId: '',
    warehouseAreaId: '',
    category: '',
    locaCode: '',
    locaLen: '',
    locaWidth: '',
    locaHeight: '',
    localVolume: '',
    localBearingCapacity: '',
    tunnelNumber: '',
    shelfNumber: '',
    layerNumber: '',
    isDel: ''
  }
})
//所有仓库
const warehouseListAll = ref([])
const getListAll = async () => {
  let res = await getWarehouseListAll()
  warehouseListAll.value = res.data
}
//根据仓库Id查询仓库的库区
const warehouseAreaList = ref([])
const getList = async () => {
  let res = await getWarehouseAreaListByWarehouseId(formData.value.warehouseId)
  warehouseAreaList.value = res.data
}
//根据库区id查询库区类型
const getWarehouseAreaTypeList = async () => {
  let res = await getWarehouseAreaTypeListByWarehouseAreaId(formData.value.warehouseAreaId)
  formData.value.category = res.data.dictLabel
}
// 监听 warehouseId 的变化
watch(
  () => formData.value.warehouseId,
  (newVal, oldVal) => {
    // 当 warehouseId 发生变化时调用 getWarehouseAreaPage 方法
    if (newVal && newVal !== oldVal) {
      getList()
    } else if (!newVal) {
      // 如果清空了 warehouseAreaId，则清空库区类型
      formData.value.warehouseAreaId = ''
    }
  }
)
//监听warehouseAreaId的变化
watch(
  () => formData.value.warehouseAreaId,
  (newVal, oldVal) => {
    // 当 warehouseAreaId 发生变化且不为空时才调用
    if (newVal && newVal !== oldVal) {
      getWarehouseAreaTypeList()
    } else if (!newVal) {
      // 如果清空了 warehouseAreaId，则清空库区类型
      formData.value.category = ''
    }
  }
)
const cancle = () => {
  dialogFormVisible.value = false
  reset.value()
}
//表单校验
const rules = ref({
  warehouseId: [
    { required: true, message: '请选择仓库', trigger: 'blur' },
  ],
  warehouseAreaId: [
    { required: true, message: '请选择库区', trigger: 'blur' },
  ],
  localCode: [
    { required: true, message: '请输入库位编号', trigger: 'blur' },
  ],
  localLen: [
    { required: true, message: '请输入库位长度', trigger: 'blur' },
  ],
  localWidth: [
    { required: true, message: '请输入库位宽度', trigger: 'blur' },
  ],
  localHeight: [
    { required: true, message: '请输入库位高度', trigger: 'blur' },
  ],
  localVolume: [
    { required: true, message: '请输入库位容积', trigger: 'blur' },
  ],
  localBearingCapacity: [
    { required: true, message: '请输入库位承重', trigger: 'blur' },
  ],
  tunnelNumber: [
    { required: true, message: '请输入巷道号', trigger: 'blur' },
  ],
  shelfNumber: [
    { required: true, message: '请输入货架号', trigger: 'blur' },
  ],
  layerNumber: [
    { required: true, message: '请输入层号', trigger: 'blur' },
  ],
})
const convertSwitchToBackend = (switchValue) => {
  return switchValue ? 1 : 2
}
const ruleFormRef = ref(null)
const submit = async () => {
  if (!ruleFormRef) return
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      if (typeof formData.value.isDel === 'boolean') {
        formData.value.isDel = convertSwitchToBackend(formData.value.isDel)
      }
      let result = null
      if (formData.value.id) {
        result = await updateWarehouseLocation(formData.value)
        if (result.code == 200) {
          emits('flash')
          dialogFormVisible.value = false
          ElMessage.success('修改成功!')
          resetForm()
        } else {
          ElMessage.error('修改失败!')
        }
      } else {
        result = await addWarehouseLocation(formData.value)
        if (result.code == 200) {
          emits('flash')
          dialogFormVisible.value = false
          ElMessage.success('操作成功!')
          resetForm()
        } else {
          ElMessage.error('操作失败!')
        }
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

onMounted(() => {
  getListAll()
})
defineExpose({
  dialogFormVisible,
  title,
  reset,
  formData,
})
</script>
<template>
  <el-dialog v-model="dialogFormVisible" :title="title" width="600" :close-on-click-modal="false">
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="formData" :rules="rules" label-width="auto">
      <el-form-item label="仓库名称：" prop="warehouseId">
        <el-select v-model="formData.warehouseId" placeholder="请选择仓库" clearable style="width: 100%;">
          <el-option v-for="item in warehouseListAll" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="库区名称：" prop="warehouseAreaId">
        <el-select v-model="formData.warehouseAreaId" placeholder="请选择库区" clearable style="width: 100%;">
          <el-option v-for="item in warehouseAreaList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="库区类型：" prop="category">
        <el-input v-model="formData.category" readonly />
      </el-form-item>
      <el-form-item label="库位编号：" prop="localCode">
        <el-input v-model="formData.localCode" placeholder="请输入库位编号" />
      </el-form-item>
      <el-form-item label="库位长度(m)：" prop="localLen">
        <el-input v-model="formData.localLen" placeholder="请输入库位长度" />
      </el-form-item>
      <el-form-item label="库位宽度(m)：" prop="localWidth">
        <el-input v-model="formData.localWidth" placeholder="请输入库位宽度" />
      </el-form-item>
      <el-form-item label="库位高度(m)：" prop="localHeight">
        <el-input v-model="formData.localHeight" placeholder="请输入库位高度" />
      </el-form-item>
      <el-form-item label="库位容积(m³)：" prop="localVolume">
        <el-input v-model="formData.localVolume" placeholder="请输入库位容积" />
      </el-form-item>
      <el-form-item label="库位承重(kg)：" prop="localBearingCapacity">
        <el-input v-model="formData.localBearingCapacity" placeholder="请输入库位承重" />
      </el-form-item>
      <el-form-item label="巷道号：" prop="tunnelNumber">
        <el-input v-model="formData.tunnelNumber" placeholder="请输入巷道号" />
      </el-form-item>
      <el-form-item label="货架号：" prop="shelfNumber">
        <el-input v-model="formData.shelfNumber" placeholder="请输入货架号" />
      </el-form-item>
      <el-form-item label="层号：" prop="layerNumber">
        <el-input v-model="formData.layerNumber" placeholder="请输入层号" />
      </el-form-item>
      <el-form-item label="是否有效：" prop="isDel">
        <el-switch v-model="formData.isDel" :active-value="1" :inactive-value="2" size="large" class="mt-2"
          inline-prompt :active-icon="Check" :inactive-icon="Close" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancle()">取消</el-button>
        <el-button type="primary" @click="submit()"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style scoped></style>